#include "head.h"

// 得到 path 文件的 id
int get_path_id(MYSQL* mysql, const char* path, int uid, int* path_id); 
// 查询以 path id 为父亲id 结果并发送
int get_son(MYSQL* mysql, int path_id, int sock_fd);
// ls
int to_ls(messenger_t* msg, int sock_fd, MYSQL* mysql)
{
    // 切割参数
    char* path = msg->args;

    // 得到用户的id // 解密 TOKEN
    int uid = 0;
    l8w8jwt_uid(msg->token, &uid);

    // 得到 path 文件的 id
    int path_id = 0;
    get_path_id(mysql, path, uid, &path_id);

    // 查询以 path id 为父亲id 结果并发送
    get_son(mysql, path_id, sock_fd);

    printf("ls 结束\n");

    return 0;
}

// 得到 path 文件的 id
int get_path_id(MYSQL* mysql, const char* path, int uid, int* path_id)
{
    char sql[200] = {0};
    sprintf(sql, "select * from file where file_usr = %d and file_path = '%s' and file_exist = 0", uid, path);
    if(mysql_query(mysql, sql) != 0)
        LOG_MSG("mysql_query");
    
    MYSQL_RES* res = mysql_store_result(mysql);
    MYSQL_ROW line = mysql_fetch_row(res);

    *path_id = atoi(line[0]);

    return 0; 
}

// 查询以 path id 为父亲id 结果并发送
int get_son(MYSQL* mysql, int path_id, int sock_fd)
{
    char sql[200] = {0};
    sprintf(sql, "select * from file where file_father_id = %d and file_exist = 0 and file_intact = 0", path_id);
    if(mysql_query(mysql, sql) != 0)
        LOG_MSG("mysql_query");

    MYSQL_RES* res = mysql_store_result(mysql);
    uint64_t rows = mysql_num_rows(res);
    if(res == NULL || rows == 0)
    {
        close(sock_fd);
        return 0;
    }

    MYSQL_ROW line;
    for(int i = 0; i < rows; ++i)
    {
        line = mysql_fetch_row(res);
        if(line == NULL)
            break;

        char name[200] = {0};
        char type[10] = {0};
        char size[20] = {0};
        strcpy(name, line[3]);
        strcpy(type, line[6]);
        strcpy(size, line[9]);
        send(sock_fd, name, sizeof(name), MSG_NOSIGNAL);
        send(sock_fd, type, sizeof(type), MSG_NOSIGNAL);
        send(sock_fd, size, sizeof(size), MSG_NOSIGNAL);
    }
    mysql_free_result(res);
    int ret = 299;
    send(sock_fd, &ret, sizeof(int), MSG_NOSIGNAL);

    return 0;     
}